import listCode from '@/utils/toCode/ml/list'
import appCode from '@/utils/toCode/ml/app'
import mainCode from '@/utils/toCode/ml/main'
import styleCode from '@/utils/toCode/ml/style'
import utilsIndexCode from '@/utils/toCode/ml/utils/index'
import tsxEdit from '@/utils/toCode/tsxEdit'
import type { addEditState, initFormState, questionSideListState } from '@/types/baseConfig'
import { getRowValue, getRule, mergeParams } from '@/utils/dyForm'
import { deepClone } from '@/utils/index'

export function getCodeList(type: 'tsx' = 'tsx', addEditInfo: addEditState) {
  const initQueryForm = getQueryForm(addEditInfo.questions, [], {})
  let tsxEditText = tsxEdit
  function stringifyWithMethods(obj: any) {
    const replacer = (key: string, value: any) => {
      if (typeof value === 'function') {
        return value.toString()
      } else {
        return value
      }
    }
    return JSON.stringify(obj, replacer, 2)
  }
  const arr = [
    {
      label: `$t('queryForm')`,
      value: JSON.stringify(initQueryForm)
    },
    {
      label: `$t('rules')`,
      value: getRuleText(addEditInfo.questions)
    }
  ]
  arr.forEach((el: any) => {
    tsxEditText = tsxEditText.replaceAll(el.label, el.value)
  })
  if (type === 'tsx') {
    return [
      {
        uid: 'components001',
        name: 'components',
        type: 'folder',
        isOpen: false,
        childer: [
          {
            uid: 'MacHeader',
            name: 'MacHeader.tsx',
            type: 'tsx',
            language: 'typescript',
            code: listCode
          }
        ]
      },
      {
        uid: '001',
        name: 'views',
        type: 'folder',
        isOpen: true,
        childer: [
          {
            uid: '002',
            name: 'list',
            type: 'folder',
            isOpen: true,
            childer: [
              {
                uid: '003',
                name: 'components',
                type: 'folder',
                isOpen: true,
                childer: [
                  {
                    uid: 'Edit',
                    name: 'Edit.tsx',
                    type: 'tsx',
                    language: 'typescript',
                    code: tsxEditText
                  }
                ]
              },
              {
                uid: '004',
                name: 'index.tsx',
                type: 'tsx',
                language: 'typescript',
                code: listCode
              }
            ]
          }
        ]
      },
      {
        uid: 'utils001',
        name: 'utils',
        type: 'folder',
        isOpen: false,
        childer: [
          {
            uid: 'utils002',
            name: 'index.ts',
            type: 'tsx',
            language: 'typescript',
            code: utilsIndexCode
          }
        ]
      },
      {
        uid: '005',
        name: 'app.tsx',
        type: 'tsx',
        language: 'typescript',
        code: appCode
      },
      {
        uid: '008',
        name: 'style.css',
        type: 'css',
        language: 'css',
        code: styleCode
      },
      {
        uid: '006',
        name: 'main.ts',
        type: 'tsx',
        language: 'typescript',
        code: mainCode
      }
    ]
  }
}

export function getQueryForm(
  questions: questionSideListState[],
  initForm: initFormState[],
  row: any
) {
  let params: any = {}
  if (initForm.length > 0) {
    initForm.forEach((el: initFormState) => {
      if (['assembly', 'local'].includes(el.type)) {
        if (row) {
          const rowValue = getRowValue(deepClone(row), el.oldKey)
          if (el.newKey.includes('.')) {
            const labelKeyArr = el.newKey.split('.')
            const newParams = getChilderParams(labelKeyArr, 0, {}, rowValue)
            params = mergeParams(params, newParams)
          } else {
            params[el.newKey] = rowValue
          }
          questions.filter((item: questionSideListState, index: number) => {
            if (item.commonForm.labelKey === el.newKey) {
              questions[index].commonForm.defaultValue = row[el.oldKey]
            }
          })
        }
      } else {
        params[el.newKey] = el.oldKey
      }
    })
  } else if (row?.id) {
    params.id = row.id
    questions.map((el: questionSideListState) => {
      el.commonForm.defaultValue = getRowValue(deepClone(row), el.commonForm.labelKey)
      return el
    })
  }
  return getParams(questions, params, initForm)
}

/**
 *  获取子对象
 * */
export function getChilderParams(
  labelKeyArr: string[],
  index: number,
  childerParams: any,
  defaultValue: any
) {
  if (index === labelKeyArr.length - 1) {
    childerParams[labelKeyArr[index]] = defaultValue
  } else if (!childerParams[labelKeyArr[index]]) {
    childerParams[labelKeyArr[index]] = getChilderParams(labelKeyArr, index + 1, {}, defaultValue)
  }
  return childerParams
}

/**
 *  字符串转成对象
 * */
const getParams = (arr: questionSideListState[], params: any = {}, initForm: initFormState[]) => {
  //  排除继承或自定义初始化数据
  arr
    .filter((el: questionSideListState) => {
      return !initForm.some((item: initFormState) => {
        return item.newKey === el.commonForm.labelKey
      })
    })
    .forEach((el: questionSideListState) => {
      if (el.type === 'RowLayout') {
        if (el?.RowLayoutForm) {
          params = {
            ...params,
            ...getParams(el.RowLayoutForm.childer, params, initForm)
          }
        }
      } else if (el.commonForm.labelKey.includes('.')) {
        const labelKeyArr = el.commonForm.labelKey.split('.')
        const newParams = getChilderParams(labelKeyArr, 0, {}, el.commonForm.defaultValue)
        params = mergeParams(params, newParams)
      } else {
        params[el.commonForm.labelKey] = el.commonForm.defaultValue
      }
    })
  return params
}
const getRuleText = (questions: questionSideListState[]) => {
  const ruleInfo = getArrRule(questions)
  let text = `{`
  const keys = Object.keys(ruleInfo)
  keys.forEach((el: string, index: number) => {
    text += `\r           ${el}: [`
    const count = ruleInfo[el].length - 1
    ruleInfo[el].forEach((item: string, n: number) => {
      text += item
      if (n !== count) {
        text += ','
      }
    })
    text += ']'
    if (index !== keys.length - 1) {
      text += ','
    }
  })
  text += '\r          }'
  return text
}
/**
 *  获取rules
 * */
const getArrRule = (arr: questionSideListState[]) => {
  let ruleInfo: any = {}
  arr.forEach((el: questionSideListState) => {
    if (el.type === 'RowLayout') {
      if (el.RowLayoutForm && el.RowLayoutForm.childer.length > 0) {
        const newRuleInfo = getArrRule(el.RowLayoutForm.childer)
        ruleInfo = mergeParams(ruleInfo, newRuleInfo)
      }
    } else {
      if (el.commonForm.labelKey.includes('.')) {
        const labelKeyArr = el.commonForm.labelKey.split('.')
        const newParams = getChilderParams(labelKeyArr, 0, {}, getRule(el, {}, true))
        ruleInfo = mergeParams(ruleInfo, newParams)
      } else {
        ruleInfo[el.commonForm.labelKey] = getRule(el, {}, true)
      }
    }
  })
  return ruleInfo
}
